import ApiResult from "@/api/base/ApiResult";
import { request, post } from "@/utils/request";
import { ElMessage } from "element-plus";
import { IGoodsPageRow } from "@/api/modules/pointsMall";
import { IGoodsProduct } from "@/components/goodsCenter/types/goodsProduct";

// 对话框打开来源，normal 编辑库存按钮直接打开，onlineStatus 上下架商品时打开
export type TOpenWay = "normal" | "onlineStatus";

// 打开库存编辑对话框时的选项
export interface IShowOptions {
  openWay?: TOpenWay;
}

/**
 * 编辑商品库存的相关业务逻辑
 */
export function useEditStock() {
  const formRef = ref();
  const tableData = ref<IGoodsProduct[]>([]);
  const loading = ref(false);
  const getTableData = async (
    url: string,
    { id = null }: { id: number | null }
  ) => {
    loading.value = true;
    const rs: ApiResult<any> = await request(url, { id });
    loading.value = false;
    if (rs.code === 200) {
      tableData.value = (rs.payload ?? []).map((item: IGoodsProduct) => ({
        ...item,
        addOrDeductionStockCountSymbol_fe: "+",
        addOrDeductionStockCount_fe: 0,
      }));
    }
  };

  const formatData = () => {
    tableData.value.forEach((row) => {
      row.addOrDeductionStockCount = Number(
        (row.addOrDeductionStockCountSymbol_fe ?? "+") +
          (row.addOrDeductionStockCount_fe ?? 0)
      );
      delete row.addOrDeductionStockCountSymbol_fe;
      delete row.addOrDeductionStockCount_fe;
    });
  };

  const submit = async (url: string) => {
    return new Promise((resolve) => {
      formRef.value?.validate(async (valid: boolean, fields: any) => {
        if (valid) {
          formatData();
          const rs: ApiResult<any> = await request(url, tableData.value);

          if (rs.code === 200) {
            ElMessage.success("库存调整成功");
            resolve(rs);
          }
        }
      });
    });
  };

  const isEmpty = (val: any) => {
    return val === undefined || val === null || val === "";
  };

  const editStockRules = {
    trigger: "blur",
    validator: (rule: any, val: any, callback: any) => {
      for (let i = 0; i < tableData.value.length; i++) {
        const row = tableData.value[i];
        const _addOrDeductionStockCount = Number(
          (row.addOrDeductionStockCountSymbol_fe ?? "+") +
            (row.addOrDeductionStockCount_fe ?? 0)
        );

        if (!isEmpty(_addOrDeductionStockCount)) {
          // 填写了库存增减量
          if (
            _addOrDeductionStockCount > 0 &&
            _addOrDeductionStockCount > row.beforeStock
          ) {
            callback(
              new Error(`【第${i + 1}行】规格的库存【增】量不能大于商家库存`)
            );
          } else if (
            _addOrDeductionStockCount < 0 &&
            Math.abs(_addOrDeductionStockCount) > row.stock
          ) {
            callback(
              new Error(`【第${i + 1}行】规格的库存【减】量不能大于剩余库存`)
            );
          } else {
            callback();
          }
        } else {
          callback();
        }
      }
    },
  };

  const openWay = ref<TOpenWay>("normal");
  const isShowEditStock = ref(false);
  const isShowEditGiftPackStock = ref(false);
  const currentStockEditingRow = ref<IGoodsPageRow>();
  const showEditStock = (rowData: IGoodsPageRow, options?: IShowOptions) => {
    currentStockEditingRow.value = rowData;
    if (rowData.type === "pack") {
      isShowEditGiftPackStock.value = true;
    } else {
      isShowEditStock.value = true;
    }

    if (options?.openWay) {
      openWay.value = options.openWay;
    }
  };

  return {
    formRef,
    tableData,
    getTableData,
    submit,
    loading,

    editStockRules,

    isShowEditStock,
    isShowEditGiftPackStock,
    currentStockEditingRow,
    showEditStock,
    openWay,
  };
}
